from flask import Flask, request
from flask_cors import CORS
from flask.views import MethodView
import jwt
from datetime import datetime, timedelta

from extension import db
from models import Job, UrgentJob, Role, User, Permission, Role_User




app = Flask(__name__)
CORS().init_app(app)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///jobs.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:cf20031208@localhost:3306/campus_greening'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)


@app.cli.command()
def create():
    db.drop_all()
    db.create_all()
    Job.init_db()
    UrgentJob.init_db()
    Role.init_db()
    User.init_db()
    Role_User.init_db()
    Permission.init_db()

@app.route('/')
def hello_campus_greening():
    return 'Welcome Campus_greening'


def verify_token():
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        if auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
    if not token:
        return False
    try:
        jwt.decode(token, 'your_secret_key', algorithms=['HS256'])
        return True
    except jwt.ExpiredSignatureError:
        return False
    except jwt.InvalidTokenError:
        return False


class JobApi(MethodView):
    def get(self, job_id):
        if verify_token():
            if not job_id:
                jobs: [Job] = Job.query.all()
                results = [
                    {
                        'id': job.id,
                        'job_people': job.job_people,
                        'job_content': job.job_content,
                        "job_last_date": job.job_last_date,
                        "job_important": job.job_important,
                        "job_delay": job.job_delay,
                        "job_delay_reason": job.job_delay_reason,
                    }for job in jobs
                ]
                return{
                    'status': 'success',
                    'message': '数据查询成功',
                    'results': results
                }
            job: Job = Job.query.get(job_id)
            return {
                'status': 'success',
                'message': '数据查询成功',
                'results': {
                    'id': job.id,
                    'job_people': job.job_people,
                    'job_content': job.job_content,
                    "job_last_date": job.job_last_date,
                    "job_important": job.job_important,
                    "job_delay": job.job_delay,
                    "job_delay_reason": job.job_delay_reason,
                }
            }
        else:
            return {
                'token无效'
            }

    def post(self):
        form = request.json
        job = Job()
        job.job_people = form.get('job_people')
        job.job_content = form.get('job_content')
        job.job_last_date = form.get('job_last_date')
        job.job_important = form.get('job_important')
        job.job_delay = form.get('job_delay')
        job.job_delay_reason = form.get('job_delay_reason')
        db.session.add(job)
        db.session.commit()

        return {
            'status': 'success',
            'message': '数据添加成功'
        }

    def delete(self, job_id):
        job: Job = Job.query.get(job_id)
        db.session.delete(job)
        db.session.commit()
        return {
            'status': 'success',
            'message': '数据删除成功'
        }

    def put(self, job_id):
        form = request.json
        job: Job = Job.query.get(job_id)
        job.id = form.get('id')
        job.job_people = form.get('job_people')
        job.job_content = form.get('job_content')
        job.job_last_date = form.get('job_last_date')
        job.job_important = form.get('job_important')
        job.job_delay = form.get('job_delay')
        job.job_delay_reason = form.get('job_delay_reason')
        db.session.add(job)
        db.session.commit()
        return {
            'status': 'success',
            'message': '数据修改成功'
        }


class UrgentJobApi(MethodView):
    def get(self, job_id):
        if not job_id:
            jobs: [Job] = UrgentJob.query.all()
            results = [
                {
                    'id': job.id,
                    'job_people': job.job_people,
                    'job_content': job.job_content,
                    "job_last_date": job.job_last_date
                }for job in jobs
            ]
            return{
                'status': 'success',
                'message': '数据查询成功',
                'results': results
            }
        job: Job = Job.query.get(job_id)
        return {
            'status': 'success',
            'message': '数据查询成功',
            'results': {
                'id': job.id,
                'job_people': job.job_people,
                'job_content': job.job_content,
                "job_last_date": job.job_last_date
            }
        }

    def post(self):
        form = request.json
        job = Job()
        job.job_people = form.get('job_people')
        job.job_content = form.get('job_content')
        job.job_last_date = form.get('job_last_date')
        db.session.add(job)
        db.session.commit()

        return {
            'status': 'success',
            'message': '数据添加成功'
        }

    def delete(self, job_id):
        job: Job = Job.query.get(job_id)
        db.session.delete(job)
        db.session.commit()
        return {
            'status': 'success',
            'message': '数据删除成功'
        }

    def put(self, job_id):
        form = request.json
        job: Job = Job.query.get(job_id)
        job.id = form.get('id')
        job.job_people = form.get('job_people')
        job.job_content = form.get('job_content')
        job.job_last_date = form.get('job_last_date')
        db.session.add(job)
        db.session.commit()
        return {
            'status': 'success',
            'message': '数据修改成功'
        }


def login():
    form = request.json
    user_id = form.get('user_id')
    password = form.get('password')
    user: User = User.query.filter_by(id=user_id).first()

    if user and user.user_password == password:
        role_user :Role_User = Role_User.query.filter_by(user_id=user_id).first()
        payload = {
            'user_id': user.id,
            'username': user.user_name,
            'exp': datetime.utcnow() + timedelta(hours=1)
        }
        token = jwt.encode(payload, 'your_secret_key', algorithm='HS256')
        return {
            'role_id': role_user.role_id,
            'user_id': user.id,
            'user_name': user.user_name,
            'password': user.user_password,
            'token': token,
            'status': 'success'
        }
    else:
        return {
            'name': user_id,
            'password': password
        }


class UserApi(MethodView):
    def get(self):
        if verify_token():
            result = db.session.query(User.id, User.user_name, User.user_password, Role_User.role_id).join(
                Role_User).all()
            user_list = [
                {'id': row.id, 'user_name': row.user_name, 'user_password': row.user_password, 'role_id': row.role_id}
                for row in result]
            return user_list
        else:
            return 'token无效'

    def post(self):
        if verify_token():
            form = request.json

            user = User()
            user.id = form.get('user_id')
            user.user_name = form.get('user_name')
            user.user_password = form.get('user_password')
            user.role_id = form.get('role_id')
            db.session.add(user)
            db.session.commit()

            role_user = Role_User()
            role_user.user_id = form.get('user_id')
            role_user.role_id = form.get('role_id')
            db.session.add(role_user)

            db.session.commit()

            return {
                'status': 'success',
                'message': '用户添加成功'
            }
        else:
            return  'token无效'

    def delete(self, user_id):
        if verify_token():
            user: User = User.query.get(user_id)
            db.session.delete(user)
            db.session.commit()
            return {
                'status': 'success',
                'message': '数据删除成功'
            }
        else:
            return 'token无效'

    def put(self, user_id):
        if verify_token():
            form = request.json
            user: User = User.query.get(user_id)
            user.user_name = form.get('user_name')
            user.user_password = form.get('user_password')
            user.role_id = form.get('role_id')
            db.session.add(user)
            db.session.commit()
            return {
                'status': 'success',
                'message': '数据修改成功'
            }
        else:
            return 'token无效'


job_api = JobApi.as_view('job_api')
app.add_url_rule('/jobs', view_func=job_api, methods=['GET', ], defaults={'job_id': None})
app.add_url_rule('/jobs', view_func=job_api, methods=['POST', ])
app.add_url_rule('/jobs/<int:job_id>', view_func=job_api, methods=['GET', 'PUT', 'DELETE'])


urgent_job_api = UrgentJobApi.as_view('urgent_job_api')
app.add_url_rule('/urgent_jobs', view_func=urgent_job_api, methods=['GET', ], defaults={'job_id': None})
app.add_url_rule('/urgent_jobs', view_func=urgent_job_api, methods=['POST', ])
app.add_url_rule('/jobs/<int:job_id>', view_func=urgent_job_api, methods=['GET', 'PUT', 'DELETE'])


app.add_url_rule('/login', view_func=login, methods=['POST'])


user_api = UserApi.as_view('user_api')
app.add_url_rule('/users', view_func=user_api, methods=['GET', ])
app.add_url_rule('/users', view_func=user_api, methods=['POST', ])
app.add_url_rule('/users/<int:user_id>', view_func=user_api, methods=['PUT', 'DELETE'])

